package ru.housewife.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * @author : atroshanin
 */
public class TimeUtils {

    private static final long SECOND = 1000;
    private static final long MINUTE = SECOND * 60;
    private static final long HOUR = MINUTE * 60;
    private static final long DAY24 = HOUR * 24;

    public static int getDaysCountBetweenDateAndNow(Date date) {
        return getDaysCountBetweenDates(date.getTime(), System.currentTimeMillis());
    }

    public static int getDaysCountBetweenDates(Date from, Date to) {
        return getDaysCountBetweenDates(from.getTime(), to.getTime());
    }

    private static int getDaysCountBetweenDates(long from, long to) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(from);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        from = c.getTimeInMillis();
        return (int) ((to - from) / DAY24);
    }

    public static int getMonthsCountBetweenNowAndBeforeDate(int daysBeforeCount) {
        if (daysBeforeCount < 0) {
            throw new RuntimeException("daysBeforeCount MUST be positive");
        }

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -daysBeforeCount);
        int dateYear = c.get(Calendar.YEAR);
        int dateMonth = c.get(Calendar.MONTH);

        c = Calendar.getInstance();
        int result = 0;
        while (c.get(Calendar.YEAR) != dateYear || c.get(Calendar.MONTH) != dateMonth) {
            result++;
            c.add(-1, Calendar.MONTH);
        }
        return result;
    }

}
